import { NextRequest, NextResponse } from 'next/server'
import { withErrorHandling } from '@/lib/auth-middleware'
import { verifyToken } from '@/lib/auth-service'

export const GET = withErrorHandling(async (request: NextRequest) => {
  try {
    const authHeader = request.headers.get('authorization')
    const token = authHeader?.replace('Bearer ', '')

    if (!token) {
      return NextResponse.json(
        { error: '缺少认证令牌' },
        { status: 401 }
      )
    }

    // 验证JWT令牌
    const decoded = verifyToken(token)
    
    if (!decoded) {
      return NextResponse.json(
        { error: '无效的认证令牌' },
        { status: 401 }
      )
    }

    // 检查用户角色
    if (decoded.role !== 'ADMIN') {
      return NextResponse.json(
        { error: '权限不足' },
        { status: 403 }
      )
    }

    return NextResponse.json({
      success: true,
      data: decoded
    })

  } catch (error) {
    console.error('验证API错误:', error)
    return NextResponse.json(
      { error: '服务器内部错误' },
      { status: 500 }
    )
  }
})
